package com.sdx.common.web;

import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.sdx.common.entity.ResCloudFile;
import com.sdx.common.service.ResCloudFileService;
import com.sdx.common.utils.FileUtils;
import com.sdx.service.ConfigService;
import com.sdx.third.AliOSSApi;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: UploadController
 * @Description:
 * @author: kangbin
 * @date: 2019/3/22 10:32
 */
@RequestMapping("/common/upload")
@Controller
public class UploadController {

    @Resource
    ResCloudFileService resCloudFileService;

    /**
     *  图片上传
     * @param file
     * @param elem  绑定的元素ID  透传给前端   后台不做判断处理
     * @return
     */
    @PostMapping("/uploadImg.json")
    @ResponseBody
    public JsonResult uploadImg(MultipartFile file, String elem) {
        JsonResult result = JsonResult.success();
        String dir = DateUtil.now("yyyyMMdd");
        String subPath = "/images/cover/"+dir+"/";
        String bucketName = "sdxcomm";
        Map<String,Object> map = new HashMap<>();
        map.put("elem",elem);
        if (!FileUtils.isEmptyFile(file)) {
            try
            {
                String fileNamePair = FileUtils.upload(subPath,file);
                String storeFile = fileNamePair.split("::")[0];
                storeFile = subPath+storeFile;
                AliOSSApi.uploadLocalFile(FileUtils.getRoot()+storeFile,bucketName,storeFile.substring(1));
                String url = "https://sdxcomm."+ ConfigService.ossDomain+storeFile;
                map.put("url",url);
                resCloudFileService.insertResFile(ResCloudFile.ALI,storeFile,storeFile,"a","学校logo");
            }catch(Exception e) {
                e.printStackTrace();
                result.setCode(JsonReturnCode.IO_ERROR.getCode());
                result.setMsg(e.getMessage());
            }
        }
        result.setData(map);
        return result;
    }
}
